import { useRef, useState } from 'react'


// let num = 0  // 解决方法1

export default function Ref() {
  const inputRef = useRef<HTMLInputElement>(null)
  // 每次重新渲染count每次都被初始化为0
  // let num = 0

  let num = useRef(0)  // useRef重新渲染不会执行

  const [count,setCount] = useState<number>(0)

  const getvalue = () => {
    console.log(inputRef.current?.value);

  }

  const handleClick = () => {
    setCount(count + 1)
    
    // num = count  

    num.current = count
  }

  let timer = useRef<null | NodeJS.Timeout>(null) 

  const [time,setTime] = useState<number>(0)

  const start = () => {
    timer.current = setInterval(() => {
      // 确保了每次更新都基于前一个状态值
      setTime(pre => pre + 1)
    }, 1000);
  }

  const end = () => {
    clearInterval(timer.current)
  }

  return (
    <>
      <h1>useRef dom引用和数据存储</h1>
      <input ref={inputRef} type="text" />
      <button onClick={getvalue}>获取input</button>
      
      <div>数据存储</div>
      {/* <div>{ count }:{ num }</div> */}
      <div>{ count }:{ num.current }</div>
      <button onClick={handleClick}>增加count</button>

      <div>计时器</div>
      <div>{ time }</div>
      <button onClick={start}>开始</button>
      <button onClick={end}>结束</button>
    </>
  )
}